import userApi from '@/api/userApi'
import type { Params, UserItem } from '@/types/userType'
import { formatDate } from '@/utils'
import { Button, Form, Input, Select, Space, Table, type TableColumnsType } from 'antd'
import { useRef, useState } from 'react'
import CreateUser from './CreateUser'
import type { IAction } from '@/types/modal'
import { message, modal } from '@/utils/AntdGlobal'
import { useAntdTable } from 'ahooks'
import AuthButton from '@/components/AnthButton'

const UserList = () => {
  const [form] = Form.useForm()
  const [ids, setIds] = useState<number[]>([])
  const getTableData = (
    { current, pageSize }: { current: number; pageSize: number },
    formData: Params
  ): Promise<{ total: number; list: UserItem[] }> => {
    return userApi.getUserList({ ...formData, pageNum: current, pageSize }).then(res => ({
      total: res.page.total,
      list: res.list
    }))
  }
  const { tableProps, search } = useAntdTable(getTableData, { form })
  const userRef = useRef<{ open: (type: IAction, data?: UserItem) => void }>(undefined)
  const handleCreate = () => {
    userRef.current?.open('create')
  }
  const handleEdit = (data: UserItem) => {
    userRef.current?.open('edit', data)
  }
  const handleDel = (userId: number) => {
    modal.confirm({
      title: '删除确认',
      content: <span>确认删除该用户吗？</span>,
      onOk: () => {
        handleUserDelSubmit([userId])
      }
    })
  }
  const handleUserDelSubmit = async (ids: number[]) => {
    await userApi.userDel({ userIds: ids })
    message.warning('删除成功')
    setIds([])
  }
  const handlePatchConfirm = () => {
    if (ids.length === 0) {
      message.error('请选择要删除的用户')
      return
    }
    modal.confirm({
      title: '删除确认',
      content: <span>确认删除该批用户吗？</span>,
      onOk: () => {
        handleUserDelSubmit(ids)
      }
    })
  }
  const columns: TableColumnsType<UserItem> = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      key: 'userId'
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: '用户邮箱',
      dataIndex: 'userEmail',

      key: 'userEmail'
    },
    {
      title: '用户角色',
      dataIndex: 'role',
      key: 'role',
      render: (role: number) => {
        return {
          0: '超级管理员',
          1: '管理员',
          2: '体验管理员',
          3: '普通用户'
        }[role]
      }
    },
    {
      title: '用户状态',
      dataIndex: 'state',
      key: 'state',
      render: (state: number) => {
        return {
          1: '在职',
          2: '离职',
          3: '实习期'
        }[state]
      }
    },
    {
      title: '注册时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (createTime: Date) => {
        return formatDate(createTime)
      }
    },
    {
      title: '最后登录时间',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      render: (lastLoginTime: Date) => {
        return formatDate(lastLoginTime)
      }
    },
    {
      title: '操作',
      render: record => {
        return (
          <Space>
            <Button type='text' onClick={() => handleEdit(record)}>
              编辑
            </Button>
            <Button type='text' danger onClick={() => handleDel(record.userId)}>
              删除
            </Button>
          </Space>
        )
      }
    }
  ]

  return (
    <div className='user-list'>
      <Form className='search-form' form={form} layout='inline' initialValues={{ state: 0 }}>
        <Form.Item label='用户ID' name='userId'>
          <Input placeholder='请输入用户ID' />
        </Form.Item>
        <Form.Item label='用户名称' name='userName'>
          <Input placeholder='清输入用户名称' />
        </Form.Item>
        <Form.Item label='状态' name='state'>
          <Select
            style={{ width: 120 }}
            options={[
              { value: 0, label: '所有' },
              { value: 1, label: '在职' },
              { value: 2, label: '离职' },
              { value: 3, label: '试用期' }
            ]}
          />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type='primary' onClick={search.submit}>
              搜索
            </Button>
            <Button onClick={search.reset}>重置</Button>
          </Space>
        </Form.Item>
      </Form>
      <div className='base-table'>
        <div className='header-wrapper'>
          <div className='title'>用户列表</div>
          <div className='action'>
            <AuthButton auth='user@create' type='primary' onClick={handleCreate}>
              新增
            </AuthButton>
            <Button danger onClick={handlePatchConfirm}>
              批量删除
            </Button>
          </div>
        </div>
        <Table
          {...tableProps}
          rowSelection={{
            type: 'checkbox',
            selectedRowKeys: ids,
            onChange: (selectedRowKeys: React.Key[]) => {
              setIds(selectedRowKeys as number[])
            }
          }}
          columns={columns}
          rowKey='userId'
          bordered
        />
      </div>
      <CreateUser mRef={userRef} update={search.submit} />
    </div>
  )
}

export default UserList
